<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>

    <a-card :bordered="false">
      <a-form-model ref="form" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
        <h3 class="title">自定义分类设置</h3>
        <a-form-model-item label="选项卡名称" prop="name">
          <div style="display: flex">
            <a-input v-model="tabName" placeholder="请输入活动名称" class="maxWidth" />
            <a-button style="margin-left: 12px" type="primary" @click="handle('addTab')"> 添加 </a-button>
          </div>

          <div class="tag">
            <a-tag closable @close="handle('remove', item)" v-for="(item, index) of conf" :key="index">{{
              item.tab
            }}</a-tag>
          </div>
        </a-form-model-item>

        <a-divider />
        <h3 class="title">推荐商品设置</h3>
        <a-form-model-item label="选择选项卡">
          <a-select v-model="tabActive" style="width: 468px">
            <a-select-option :value="item.tab" :key="index" v-for="(item, index) of conf">
              {{ item.tab }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="选择商品">
          <div class="lineBox">
            <div class="lineBoxNav">
              <div class="box">
                <div
                  :class="['item', item.index === active ? 'active' : '']"
                  v-for="item of tabNav"
                  :key="item.index"
                  @click="handle('change', item)"
                >
                  {{ item.title }}
                </div>
              </div>
            </div>

            <div class="goodsSelect" v-show="!active">
              <div class="lineBoxStyle">
                <div class="tit">添加商品：</div>
                <div class="inp">
                  <a-input disable />
                </div>
                <a-button style="margin-left: 12px" type="primary" @click="handle('select')"> 选择 </a-button>
              </div>

              <a-table :data-source="getItem ? getItem.goods_ids : []" :columns="columns" :pagination="false">
                <div slot="content" slot-scope="scope, text">
                  <div class="imgTxt">
                    <div class="img">
                      <img :src="text.cover_pic" alt="" />
                    </div>
                    <div class="txt">
                      <div class="name">{{ text.name }}</div>
                    </div>
                  </div>
                </div>

                <div slot="actions" slot-scope="scope, text, index">
                  <a-button type="link" @click="handle('removeGoods', index)" size="small">删除</a-button>
                </div>
              </a-table>
            </div>
            <div class="lineBoxStyle" v-show="active">
              <div class="tit">添加分类：</div>
              <div class="inp">
                <a-tree-select
                  :value="getItem ? getItem.cat_ids : []"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="选择分类"
                  tree-default-expand-all
                  allowClear
                  @change="changeCat"
                >
                  <a-tree-select-node :key="item.id" :value="item.id" :title="item.name" v-for="item in catList">
                    <a-tree-select-node :key="cat.id" :value="cat.id" :title="cat.name" v-for="cat in item.children">
                    </a-tree-select-node>
                  </a-tree-select-node>
                </a-tree-select>
              </div>
            </div>
          </div>
        </a-form-model-item>

        <div class="btnBox">
          <a-button v-loading="btnLoading" :disabled="disabled" type="primary" @click="onSubmit"> 提交 </a-button>
          <a-button style="margin-left: 10px" @click="$router.go(-1)"> 取消 </a-button>
        </div>
      </a-form-model>
    </a-card>

    <popGoods @onOk="selectGoods" ref="popGoods"></popGoods>
  </page-header-wrapper>
</template>

<script>
import { pushGoods, pushGoodsSave, Info } from '@/api/marketing/activityNew'
import popGoods from '../seckill/components/goods.vue'
import { list as catList } from '@/api/goods/cat'

export default {
  components: {
    popGoods,
  },

  computed: {
    getItem() {
      let { tabActive, conf } = this
      if (!tabActive || !conf.length) return []

      let item = conf.find((el) => el.tab === tabActive)
      return item
    },
  },

  data() {
    return {
      btnLoading: false,
      disabled: false,

      columns: [
        {
          title: '商品名称',
          dataIndex: 'content',
          scopedSlots: { customRender: 'content' },
        },
        {
          title: '操作',
          dataIndex: 'actions',
          width: 80,
          scopedSlots: { customRender: 'actions' },
        },
      ],

      conf: [],
      tabNav: [
        { title: '手动选择', index: 0 },
        { title: '选择分类', index: 1 },
      ],
      active: 0,
      tabActive: '',
      catList: [],
    }
  },

  methods: {
    getIndex() {
      let { tabActive, conf } = this,
        index = conf.findIndex((el) => el.tab === tabActive)

      return index
    },

    changeCat(e) {
      if (!this.tabActive) return this.$message.error('请先选择选项卡')
      let index = this.getIndex()
      if (index !== -1) {
        this.$set(this.conf[index], 'cat_ids', e)
        this.$set(this.conf[index], 'goods_ids', [])
      }
    },

    openGoods() {
      if (!this.tabActive) return this.$message.error('请先选择选项卡')
      let goods = this.conf[this.getIndex()].goods_ids
      goods = goods.map((el) => {
        el.id = String(el.id)
        return el
      })
      this.$nextTick(() => {
        this.$refs.popGoods.visible = true
        this.$refs.popGoods.selectGoodsList = goods
      })
    },

    selectGoods(list) {
      let index = this.getIndex()

      if (index !== -1) {
        this.$set(this.conf[index], 'goods_ids', list)
        this.$set(this.conf[index], 'cat_ids', '')
      }
    },

    handle(type, param) {
      switch (type) {
        case 'change':
          if (this.active === param.index) {
            return
          }

          this.active = param.index
          break

        case 'addTab':
          let { tabName: tab } = this
          if (!tab) return this.$message.error('选项卡名称不能为空')

          this.conf.push({
            tab,
            goods_ids: [],
            cat_ids: '',
          })

          this.tabName = ''
          break

        case 'remove':
          if (this.tabActive === param.tab) {
            this.tabActive = ''
          }
          this.conf.splice(param.index, 1)
          break

        case 'select':
          this.openGoods()
          break

        case 'removeGoods':
          this.conf[this.getIndex()].goods_ids.splice(param, 1)
          break
      }
    },

    // 点击提交
    async onSubmit() {
      let form = JSON.parse(JSON.stringify(this.conf))

      if (!form.length) {
        return this.$message.error('请添加至少一项!')
      }

      form.forEach((e) => {
        if (e.goods_ids.length) {
          e.goods_ids = e.goods_ids.map((el) => el.id)
        }
      })

      this.btnLoading = true
      const res = await pushGoodsSave({
        conf: form,
      })
      this.btnLoading = false
      if (!res.code) {
        this.$message.success(res.msg)
        return
      }
      this.$message.error(res.msg)
    },
  },

  async mounted() {
    const hide = this.$message.loading('请稍等', 0)

    let catRes = await catList()
    if (!catRes.code && catRes.data.list) {
      this.catList = catRes.data.list || []
    }

    let res = await pushGoods()
    if (!res.code && res.data && res.data.conf) {
      let conf = res.data.conf
      conf.forEach((el) => {
        el.goods_ids = el.goods_list
        delete el.goods_list
      })
      this.conf = conf

      console.log('conf,', conf)
    }
    hide()
  },
}
</script>

<style lang="less" scoped>
.title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 14px;
  font-weight: bold;
}

.flex {
  display: flex;

  .slot {
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    height: 32px;
    width: 32px;
    background: rgba(247, 247, 247, 1);
    text-align: center;
  }
}

.maxWidth {
  width: 480px;
}

.imgTxt {
  display: flex;

  .img {
    width: 50px;
    height: 50px;

    img {
      display: block;
      width: 100%;
      height: 100%;
    }
  }

  .txt {
    flex: 1;
    overflow: hidden;
    margin-left: 10px;
  }

  .name {
    display: -webkit-box;
    white-space: normal;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
    overflow: hidden;
  }
}

.btnBox {
  text-align: center;
}

.lineBox {
  width: 548px;
  border: 1px solid rgba(0, 0, 0, 0.149);
  padding: 16px 80px 16px 11px;
  border-radius: 4px;
  overflow: hidden;
}

.lineBoxNav {
  display: flex;

  .box {
    background: #f3f3f3;
    padding: 3px;
    border-radius: 4px;
    overflow: hidden;
  }

  .item {
    float: left;
    width: 84px;
    height: 26px;
    line-height: 26px;
    font-size: 14px;
    color: #262626;
    text-align: center;
    overflow: hidden;
    cursor: pointer;

    &.active {
      background: #fff;
      border-radius: 4px;
    }
  }
}

.lineBoxStyle {
  display: flex;
  padding: 24px 0;

  .inp {
    flex: 1;
    overflow: hidden;
  }
}
</style>
